package retrofit.boot.annotation;

import lombok.Data;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.PriorityOrdered;
import org.springframework.util.Assert;
import retrofit.boot.autoconfigure.RetrofitContext;
import retrofit.boot.client.RetrofitLogger;
import retrofit.boot.constants.RetrofitOrder;

/**
 * Created by wulg on 2019/11/5
 * description:
 */
@Data
public final class RetrofitClientFactoryBean implements FactoryBean<Object>, InitializingBean, PriorityOrdered {

    private Class<?> type;

    private String name;

    @Autowired
    private RetrofitContext retrofitContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.hasText(this.name, "Name must be set");
        Assert.isTrue(this.type.isInterface(), "Type must be an interface class");
    }

    @Override
    public Object getObject() throws Exception {
        return retrofitContext.getRetrofitClientBuilder(this.name)
                .setEndpoint(retrofitContext.getEndpoint(this.name))
                .setLog(new RetrofitLogger(type))
                .build()
                .create(type);
    }

    @Override
    public Class<?> getObjectType() {
        return this.type;
    }

    @Override
    public int getOrder() {
        return RetrofitOrder.getClientOrder();
    }
}
